<template>
  <div v-if="props.visible" class="auth-modal-overlay">
    <div class="auth-modal-container">
      <div class="auth-modal-header">
        <h3>{{ currentTab === 'login' ? '登录系统' : '用户注册' }}</h3>
        <button class="close-btn" @click="closeModal">
          <n-icon size="20">
            <Close />
          </n-icon>
        </button>
      </div>
      
      <div class="auth-modal-content">
        <!-- 登录表单 -->
        <div v-if="currentTab === 'login'" class="auth-form">
          <n-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            label-placement="top"
          >
            <n-form-item label="用户名" path="username">
              <n-input
                v-model:value="loginForm.username"
                placeholder="请输入用户名"
                :prefix-icon="Person"
              />
            </n-form-item>
            
            <n-form-item label="密码" path="password">
              <n-input
                v-model:value="loginForm.password"
                :type="showLoginPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                :prefix-icon="LockClosed"
                @keyup.enter="handleLogin"
              >
                <template #suffix>
                  <n-icon
                    size="16"
                    class="password-toggle"
                    @click="showLoginPassword = !showLoginPassword"
                  >
                    <Eye v-if="showLoginPassword" />
                    <EyeOff v-else />
                  </n-icon>
                </template>
              </n-input>
            </n-form-item>
            
            <n-form-item>
              <n-checkbox v-model:checked="loginForm.rememberMe">记住我</n-checkbox>
            </n-form-item>
            
            <n-form-item>
              <n-button
                type="primary"
                block
                @click="handleLogin"
                :loading="loginLoading"
              >
                {{ loginLoading ? '登录中...' : '登录' }}
              </n-button>
            </n-form-item>
            
            <div class="auth-switch">
              <span>还没有账号？</span>
              <n-button type="link" as any @click="switchTab('register')">
                立即注册
              </n-button>
            </div>
          </n-form>
        </div>
        
        <!-- 注册表单 -->
        <div v-else class="auth-form">
          <n-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            label-placement="top"
          >
            <n-form-item label="用户名" path="username">
              <n-input
                v-model:value="registerForm.username"
                placeholder="请输入用户名"
                :prefix-icon="Person"
              />
            </n-form-item>
            
            <n-form-item label="密码" path="password">
              <n-input
                v-model:value="registerForm.password"
                :type="showRegisterPassword ? 'text' : 'password'"
                placeholder="请输入密码（至少6位）"
                :prefix-icon="LockClosed"
              >
                <template #suffix>
                  <n-icon
                    size="16"
                    class="password-toggle"
                    @click="showRegisterPassword = !showRegisterPassword"
                  >
                    <Eye v-if="showRegisterPassword" />
                    <EyeOff v-else />
                  </n-icon>
                </template>
              </n-input>
            </n-form-item>
            
            <n-form-item label="确认密码" path="confirmPassword">
              <n-input
                v-model:value="registerForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="请再次输入密码"
                :prefix-icon="LockClosed"
                @keyup.enter="handleRegister"
              >
                <template #suffix>
                  <n-icon
                    size="16"
                    class="password-toggle"
                    @click="showConfirmPassword = !showConfirmPassword"
                  >
                    <Eye v-if="showConfirmPassword" />
                    <EyeOff v-else />
                  </n-icon>
                </template>
              </n-input>
            </n-form-item>
            
            <n-form-item label="邮箱（可选）" path="email">
              <n-input
                v-model:value="registerForm.email"
                placeholder="请输入邮箱"
                :prefix-icon="Mail"
              />
            </n-form-item>
            
            <n-form-item>
              <n-button
                type="primary"
                block
                @click="handleRegister"
                :loading="registerLoading"
              >
                {{ registerLoading ? '注册中...' : '注册' }}
              </n-button>
            </n-form-item>
            
            <div class="auth-switch">
              <span>已有账号？</span>
              <n-button type="link" as any @click="switchTab('login')">
                立即登录
              </n-button>
            </div>
          </n-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Person, LockClosed, Mail, Close, Eye, EyeOff } from '@vicons/ionicons5'
import { useUserStore } from '../stores/user'
import { useMessage } from 'naive-ui'
import { authService } from '../services/auth-service'

// 定义组件属性
interface Props {
  visible: boolean
}

// 定义组件事件
interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'login-success'): void
}

// Props are used directly in template
const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const userStore = useUserStore()
const message = useMessage()

// 表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 当前标签页
const currentTab = ref<'login' | 'register'>('login')

// 加载状态
const loginLoading = ref(false)
const registerLoading = ref(false)

// 控制密码显示状态
const showLoginPassword = ref(false)
const showRegisterPassword = ref(false)
const showConfirmPassword = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: true
})

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: ''
})

// 登录表单验证规则
const loginRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ]
}

// 注册表单验证规则
const registerRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '密码长度至少为6位',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码',
      trigger: 'blur'
    },
    {
      validator: (_rule: any, value: string) => {
        if (!value || registerForm.password === value) {
          return new Promise((resolve) => resolve(true))
        }
        return new Promise((_resolve, reject) => {
          reject(new Error('两次输入的密码不一致'))
        })
      },
      trigger: 'blur'
    }
  ],
  email: [
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入有效的邮箱地址',
      trigger: 'blur',
      required: false
    }
  ]
}

// 关闭模态框
const closeModal = () => {
  emit('update:visible', false)
}

// 切换标签页
const switchTab = (tab: 'login' | 'register') => {
  currentTab.value = tab
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    const valid = await loginFormRef.value.validate()
    if (valid) {
      loginLoading.value = true
      
      const loginResponse = await authService.login({
        username: loginForm.username,
        password: loginForm.password
      })
      
      if (loginResponse && loginResponse.code === 0) {
        // 登录成功，保存用户信息
        const userData: any = loginResponse.data
        
        // 保存token到localStorage和store
        if (userData.token) {
          localStorage.setItem('auth_token', userData.token)
          userStore.setToken(userData.token)
        }
        
        // 保存refreshToken（如果有）
        if (userData.refreshToken) {
          localStorage.setItem('refresh_token', userData.refreshToken)
          userStore.setRefreshToken(userData.refreshToken)
        }
        
        // 保存用户信息到store
        if (userData.user) {
          userStore.setUserInfo(userData.user)
          userStore.setUserId(userData.user.id || 0)
        } else {
          // 如果没有user对象，尝试从data中获取用户信息
          const userId = (loginResponse.data as any).userId || (loginResponse.data as any).id || 0
          const username = (loginResponse.data as any).username || ''
          const nickname = (loginResponse.data as any).nickname || username
          const role = (loginResponse.data as any).role || ''
          
          userStore.setUserInfo({
            id: userId,
            username,
            nickname,
            role
          })
          userStore.setUserId(userId)
        }
        
        // 如果设置了记住我，保存用户名
        if (loginForm.rememberMe) {
          localStorage.setItem('remembered_username', loginForm.username)
        } else {
          localStorage.removeItem('remembered_username')
        }
        
        // 显示成功消息
        message.success('登录成功')
        
        // 触发登录成功事件
        emit('login-success')
        
        // 延迟关闭模态框，确保token已设置到全局请求头
        setTimeout(() => {
          // 关闭模态框
          closeModal()
          
          // 重置表单
          loginForm.username = ''
          loginForm.password = ''
        }, 500)
      } else {
        message.error('登录失败')
      }
    }
  } catch (error) {
    console.error('登录失败:', error)
    message.error('登录失败，请检查用户名和密码')
  } finally {
    loginLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    const valid = await registerFormRef.value.validate()
    if (valid) {
      registerLoading.value = true
      
      const result = await authService.register({
        username: registerForm.username,
        password: registerForm.password,
        email: registerForm.email
      })
      
      if (result && result.code === 0) {
        // 显示成功提示
        message.success(result.data || '注册成功，请登录')
        
        // 切换到登录页面
        switchTab('login')
        
        // 预填充用户名
        loginForm.username = registerForm.username
        
        // 重置注册表单
        registerForm.username = ''
        registerForm.password = ''
        registerForm.confirmPassword = ''
        registerForm.email = ''
      } else {
        throw new Error(result?.msg || '注册失败，请稍后重试')
      }
    }
  } catch (error) {
    console.error('注册失败:', error)
    if (error instanceof Error) {
      message.error(error.message || '注册失败，请稍后重试')
    } else {
      message.error('注册失败，请稍后重试')
    }
  } finally {
    registerLoading.value = false
  }
}

// 组件挂载时，如果有记住的用户名，则自动填充
const rememberedUsername = localStorage.getItem('remembered_username')
if (rememberedUsername) {
  loginForm.username = rememberedUsername
  loginForm.rememberMe = true
}
</script>

<style scoped>
.auth-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.auth-modal-container {
  width: 400px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.auth-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.auth-modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  transition: color 0.3s;
}

.close-btn:hover {
  color: #333;
}

.auth-modal-content {
  padding: 24px;
}

.auth-form {
  width: 100%;
}

.auth-switch {
  text-align: center;
  margin-top: 16px;
}

.auth-switch span {
  color: #666;
}

.password-toggle {
  cursor: pointer;
  color: #999;
  transition: color 0.3s;
}

.password-toggle:hover {
  color: #666;
}
</style>